<?php
/**
 * 商品售后
 */

use app\config\Db;
use Core\Common\Common;
use Core\Result\Result;
use Core\Utils\Utils;


/**
 * 售后列表
 * @param $data
 * @return void
 */
function aftersalesList($data)
{
    $user_id = Common::getUser_id($data);
    $db = new Db();
    $aftersalesSql = "select ya.`aftersale_id`,`aftersale_type`,`status`,`pics`,`description`,`reply`,`add_time`,`tracking_no`,ya.`logistics_name`,`return_address`,`aftersale_reason`,`aftersales_sn`,ya.`order_id`,ya.`user_id`,`refund_amount`,`audit_time`,`deal_time`,`final_time`,`order_item_id`,`number`,`sku_id`,`goods_id`,`order_number`,sgo.order_pay_price from `ysmz_aftersales` as ya inner join `ysmz_aftersales_item` as ai on ya.aftersale_id = ai.aftersale_id inner join `ysmz_shop_goods_order` as sgo on ya.order_id = sgo.order_id where ya.`user_id` = '$user_id'";
    $aftersalesInfo = $db->query($aftersalesSql);
    $goodsIds = implode(',', array_column($aftersalesInfo, 'goods_id'));
    $goodsSkuIds = implode(',', array_column($aftersalesInfo, 'sku_id'));
    $goodsInfo = $db->query("select goods_id,name,free_shipping,fixed_shipping_fee from ysmz_shop_goods where `goods_id` in($goodsIds)", 'goods_id');
    $SkuInfo = $db->query("select sku_id,sku_name,sku_img_id,spec_info from ysmz_shop_goods_sku where sku_id in($goodsSkuIds)", 'sku_id');
    $fileId = implode(',', array_column($SkuInfo, 'sku_img_id'));
    $fileInfo = $db->query("select file_id,storage,`domain`,file_path from ysmz_file where file_id in($fileId)");
    foreach ($fileInfo as $k => $v) {
        $fileInfo[$k]['file_url'] = Common::fileUrl($v);
    }
    $fileInfo = array_column($fileInfo, 'file_url', 'file_id');
    foreach ($SkuInfo as $k => $v) {
        $SkuInfo[$k]['sku_img_url'] = $fileInfo[$v['sku_img_id']] ?? '';
    }
    foreach ($aftersalesInfo as $k => $v) {
        $aftersalesInfo[$k]["goods_name"] = $goodsInfo[$v['order_item_id']]['name'] ?? '';
        $aftersalesInfo[$k]["typeDescription"] = getAftersaleType($v["aftersale_type"]);
        $aftersalesInfo[$k]["statusDescription"] = getStatusType($v["status"]);
        $aftersalesInfo[$k]['goods_name'] = $goodsInfo[$v['goods_id']]['name'] ?? '';
        $aftersalesInfo[$k]['sku'] = $SkuInfo[$v['sku_id']] ?? [];
        $订单规格ID = implode(',', json_decode($SkuInfo[$v['sku_id']]['spec_info'], true));
        $订单规格信息 = $db->query("select spec_id,name from ysmz_shop_goods_spec where spec_id in($订单规格ID)");
        $订单规格信息 = implode(',', array_column($订单规格信息, 'name'));
        $aftersalesInfo[$k]['sku']['spec_name'] = $订单规格信息;
        $aftersalesInfo[$k]['spec_name'] = $订单规格信息;

    }
    Result::success($aftersalesInfo);
}
/**
 * 申请售后
 * @param $data
 * @return void
 */
function applyAftersales($data)
{
    $user_id = Common::getUser_id($data);
    $order_id = $data['order_id'];
    $aftersale_type = $data['aftersale_type'];//申请类型：1、退货退款，2、换货，3、维修，4、其它，5，仅退款
    $pics = $data['pics'];//用户凭证
    $description = $data['description'];//描述
    $aftersale_reason = $data['aftersale_reason'];//售后原因
    if($aftersale_reason==null){
        Result::error("请选择售后原因");
    }
    if(!in_array($aftersale_type,[1,2,3,4,5])){
        Result::error("请选择申请类型");
    }
    $db = new Db("host");
    $aftersalesSql = "select `aftersale_id` from `ysmz_aftersales` where `order_id` = '$order_id' and `user_id` = '$user_id'";
    $aftersalesInfo = $db->find($aftersalesSql);
    if(!empty($aftersalesInfo)){
        Result::error("订单已在售后，请勿重复提交");
    }
    $orderSql = "select `pay_status`,`order_state`,`shipping_status`,`received_time`,`order_pay_price`,`payment_type`,`shop_id`,`order_number`,`goods_id`,`order_type` from `ysmz_shop_goods_order` where `order_id` = '$order_id' and `user_id` = '$user_id'";
    $orderInfo = $db->find($orderSql);
    $shop_id = $orderInfo['shop_id'];
    $order_number = $orderInfo['order_number'];
    $goods_id = $orderInfo['goods_id'];
    if(empty($orderInfo)) Result::error("失效订单");
    /*$goodsInfo = $db->find("select goods_id,`is_support_return` from `ysmz_shop_goods` where `goods_id`={$orderInfo['goods_id']} limit 1");
    if($goodsInfo["is_support_return"] != 1){
        Result::error("商品不支持售后");
    }*/
    if($orderInfo["shipping_status"] == 3 && $orderInfo["order_type"] == 1){
        Result::error("商品已揽货，暂不支持售后");
    }
    if(!in_array($orderInfo["order_state"],[1,2])){
        Result::error("订单不可售后");
    }
    if($orderInfo["pay_status"] != 2){
        Result::error("订单未支付");
    }
    if ($orderInfo["received_time"] && isSevenDaysLaterExceeded($orderInfo["received_time"])) {
        Result::error("已超过可售后时间");
    }
    if($orderInfo["shop_id"] == 1){
        Result::error("主订单不支持售后，请重新选择");
    }
    $refund_amount = 0;
    if($aftersale_type==1 || $aftersale_type ==5){
        $refund_amount = $orderInfo["order_pay_price"];
    }
    $aftersales_sn = Utils::createOrderNo("sh");
    $aftersalesSql = "INSERT INTO `ysmz_aftersales` (`aftersale_type`, `aftersale_reason`,`status`, `pics`, `description`,`aftersales_sn`, `order_id`, `user_id`, `refund_amount`, `shop_id`) VALUES ($aftersale_type, '$aftersale_reason',1, '$pics', '$description', '$aftersales_sn', $order_id, $user_id, $refund_amount, $shop_id)";
    $upOrderSql = "update `ysmz_shop_goods_order` set `pay_status`=3 where `order_id`=$order_id and `user_id` = $user_id and `pay_status` = 2";
    $db->startTrans();
    try {
        if(!$db->save($upOrderSql)){
            Common::exception("订单更新失败");
        }
        if(!$db->save($aftersalesSql)) Common::exception("申请失败");
        $aftId = $db->mysql_insert_id();
        $aftersalesItemSql = "INSERT INTO `ysmz_aftersales_item` (`order_item_id`, `number`, `aftersale_id`) VALUES ($goods_id, $order_number,$aftId)";
        if (!$db->save($aftersalesItemSql)) Common::exception("申请失败2");
        $db->commit();
    } catch (\Exception $e) {
        Result::error($e->getMessage());
    }
    Result::success("申请成功，等待审核处理");
}
/**
 * 售后详情
 * @param $data
 * @return void
 */
function aftersalesDetails($data)
{
    $user_id = Common::getUser_id($data);
    $aftersale_id = $data['aftersale_id'];
    $db = new Db();
    $aftersalesSql = "select ya.`aftersale_id`,`aftersale_type`,`status`,`pics`,`description`,`reply`,`add_time`,`tracking_no`,ya.`logistics_name`,`return_address`,`aftersale_reason`,`aftersales_sn`,ya.`order_id`,ya.`user_id`,`refund_amount`,`audit_time`,`deal_time`,`final_time`,`order_item_id`,`number`,`sku_id`,`goods_id`,`order_number`,sgo.order_pay_price from `ysmz_aftersales` as ya inner join `ysmz_aftersales_item` as ai on ya.aftersale_id = ai.aftersale_id inner join `ysmz_shop_goods_order` as sgo on ya.order_id = sgo.order_id where ya.`aftersale_id` = $aftersale_id and ya.`user_id` = $user_id";
    $aftersalesInfo = $db->find($aftersalesSql);
    $aftersalesInfo["typeDescription"] = getAftersaleType($aftersalesInfo["aftersale_type"]);
    $aftersalesInfo["statusDescription"] = getStatusType($aftersalesInfo["status"]);
    $goodsInfo = $db->find("select goods_id,name,free_shipping,fixed_shipping_fee from `ysmz_shop_goods` where `goods_id`={$aftersalesInfo['goods_id']} limit 1");
    $SkuInfo = $db->find("select sku_id,sku_name,sku_img_id,spec_info from `ysmz_shop_goods_sku` where sku_id={$aftersalesInfo['sku_id']} limit 1");
    $fileInfo = $db->find("select file_id,storage,`domain`,file_path from ysmz_file where file_id={$SkuInfo['sku_img_id']} limit 1");
    $SkuInfo['sku_img_url'] = Common::fileUrl($fileInfo);
    $spec = implode(',', json_decode($SkuInfo['spec_info'], true));
    $specInfo = $db->query("select spec_id,name from ysmz_shop_goods_spec where spec_id in($spec)");
    $specInfo = implode(',', array_column($specInfo, 'name'));
    $aftersalesInfo['spec_name'] = $specInfo;
    $aftersalesInfo['goods'] = $goodsInfo;
    $aftersalesInfo['sku'] = $SkuInfo;
    Result::success($aftersalesInfo);
}
/**
 * 回传快递
 * @param $data
 * @return void
 */
function aftersalesReturnParcel($data)
{
    $user_id = Common::getUser_id($data);
    $aftersale_id = $data['aftersale_id'];
    $tracking_no = $data['tracking_no'];
    $logistics_name = $data['logistics_name'];
    if(empty($tracking_no) || empty($logistics_name)){
        Result::error("请输入物流信息");
    }
    $db = new Db("host");
    $aftersalesSql = "select ya.`aftersale_id`,`aftersale_type`,`status`,`pics`,`description`,`reply`,`add_time`,`tracking_no`,`logistics_name`,`return_address`,`aftersale_reason`,`aftersales_sn`,`order_id`,`refund_amount`,`audit_time`,`deal_time`,`final_time`,`order_item_id`,`number` from `ysmz_aftersales` as ya inner join `ysmz_aftersales_item` as ai on ya.aftersale_id = ai.aftersale_id where ya.`aftersale_id` = $aftersale_id and `user_id` = $user_id";
    $aftersalesInfo = $db->find($aftersalesSql);
    if(empty($aftersalesInfo)){
        Result::error("无效售后订单");
    }
    if($aftersalesInfo["status"] != 4){
        Result::error("售后未要求寄回");
    }
    $upAftersalesSql = "update `ysmz_aftersales` set `tracking_no`='$tracking_no',`logistics_name` = '$logistics_name',`status` = 5 where `aftersale_id`=$aftersale_id and `user_id` = $user_id and `status` = 4";
    if(!$db->save($upAftersalesSql)){
        Result::error("操作失败");
    }
    Result::success();
}
/**
 * 后台退款接口
 * @param $data
 * @return void
 */
function aftersalesRefund($data)
{
    $aftersale_id = $data['aftersale_id'];
    $order_id = $data['order_id'];
    $shop_id = $data['shop_id'];
    if(empty($aftersale_id) || empty($order_id) || empty($shop_id)){
        Result::error("参数错误");
    }
    $db = new Db("host");
    $aftersalesSql = "select ya.`aftersale_id`,`aftersale_type`,`status`,`pics`,`description`,`reply`,`add_time`,`tracking_no`,`logistics_name`,`return_address`,`aftersale_reason`,`aftersales_sn`,`order_id`,`refund_amount`,`audit_time`,`deal_time`,`final_time`,`order_item_id`,`number`,`user_id` from `ysmz_aftersales` as ya inner join `ysmz_aftersales_item` as ai on ya.aftersale_id = ai.aftersale_id where ya.`aftersale_id` = $aftersale_id and ya.`order_id` = $order_id and ya.`shop_id` = $shop_id";
    $aftersalesInfo = $db->find($aftersalesSql);
    if(empty($aftersalesInfo)){
        Result::error("无效售后订单");
    }
    if($aftersalesInfo["status"] >= 6 && $aftersalesInfo["status"] != 4){
        Result::error("售后订单已完成或已取消");
    }
    $data_id = $aftersalesInfo["aftersales_sn"];
    $user_id = $aftersalesInfo["user_id"];
    $refund_amount = $aftersalesInfo["refund_amount"];//退款金额
    $shopInfo = $db->find("select `shop_id`,`shop_money` from `ysmz_shop` where `shop_id`=$shop_id");
    if(empty($shopInfo)){
        Result::error("店铺不存在");
    }
    if($refund_amount > $shopInfo["shop_money"]){
        Result::error("店铺余额不足，发起退款失败");
    }
    $orderInfo = $db->find("select `order_id`,`order_pay_price`,`shipping_status`,`order_state`,`pay_status`,`payment_type` from `ysmz_shop_goods_order` where `order_id`=$order_id and `user_id`=$user_id and `is_delete`=0 limit 1");
    if (!$orderInfo) Result::error("订单信息不存在");
    if($refund_amount <= 0 || $refund_amount > $orderInfo["order_pay_price"]){
        Result::error("退款金额异常，请核对");
    }
    $userInfo = $db->find("select `cloud_bean`,`birth_bean`,`assist_bean` from `user_info` where `user_id`=$user_id");
    if (!$userInfo) Result::error("用户信息不存在");
    switch ($orderInfo["payment_type"]){
        case 6:
        case 4:
            $bean = $userInfo["birth_bean"];
            $data_src = 3;
            $setJoin = "`birth_bean`=`birth_bean` + $refund_amount";
            $whereJoin = "and `birth_bean` = $bean";
            break;
        case 7:
        case 5:
            $bean = $userInfo["assist_bean"];
            $data_src = 4;
            $setJoin = "`assist_bean`=`assist_bean` + $refund_amount";
            $whereJoin = "and `assist_bean` = $bean";
            break;
        default:
            $bean = $userInfo["cloud_bean"];
            $data_src = 1;
            $setJoin = "`cloud_bean`=`cloud_bean` + $refund_amount";
            $whereJoin = "and `cloud_bean` = $bean";
            break;
    }
    $upAftersalesSql = "update `ysmz_aftersales` set `status` = 6 where `aftersale_id`=$aftersale_id and `status` < 6";
    $upShopSql = "update `ysmz_shop` set `shop_money` = `shop_money` - $refund_amount where `shop_id`=$shop_id";
    $addShopFeeSql = "insert into `ysmz_shop_account_log`(shop_id,shop_money,type,remarks,new_shop_money,data_id) values ($shop_id,-$refund_amount,'4','退款',$shopInfo[shop_money] - $refund_amount,'$data_id')";
    $upOrderSql = "update `ysmz_shop_goods_order` set `order_state` = 5,`pay_status` = 4 where `order_id`=$order_id and `user_id`=$user_id";
    $upUserSql = "update `user_info` set $setJoin where `user_id`=$user_id $whereJoin";
    $addOrderSql = "insert into `user_balance_detail`(user_id,balance,data_src,data_id,data_remarks,update_type,new_balance) values ($user_id,$refund_amount,$data_src,'$data_id','退款',1,$bean+$refund_amount)";
    $db->startTrans();
    try {
        if(!$db->save($upAftersalesSql)) Common::exception("售后订单更新失败");
        if(!$db->save($upShopSql)) Common::exception("售后店铺余额更新失败");
        if(!$db->save($addShopFeeSql)) Common::exception("售后店铺余额明细更新失败");
        if(!$db->save($upOrderSql)) Common::exception("商品订单更新失败");
        if(!$db->save($upUserSql)) Common::exception("用户余额更新失败");
        if(!$db->save($addOrderSql)) Common::exception("用户余额明细更新失败");
        $db->commit();
    } catch (\Exception $e) {
        $db->rollback();
        Result::error($e->getMessage());
    }
    Result::success();
}
/**
 * @param $received_time
 * @return bool
 * @throws DateMalformedStringException
 */
function isSevenDaysLaterExceeded($received_time) {
    $received_date = new DateTime($received_time);
    $seven_days_later = clone $received_date;
    $seven_days_later->modify('+8 days');
    $current_time = new DateTime();

    return $seven_days_later < $current_time;
}
function getAftersaleType($aftersale_type)
{
    switch ($aftersale_type) {
        case 1 : $type = "退货退款";break;
        //case 2 : $type = "换货";break;
        case 3 : $type = "维修";break;
        case 4 : $type = "其它";break;
        case 5 : $type = "仅退款";break;
    }
    return $type;
}
function getStatusType($status)
{
    switch ($status) {
        case 1 : $type = "正在审核处理";break;
        case 2 : $type = "售后审核通过,待处理";break;
        case 3 : $type = "售后审核未通过";break;
        case 4 : $type = "售后要求寄回";break;
        case 5 : $type = "快递已寄回";break;
        case 6 : $type = "已完成";break;
        case 7 : $type = "已取消";break;
    }
    return $type;
}
